package com.hd123.rumba.qt.def;

import com.hd123.rumba.exception.BusinessException;

public class SQLTable {

  /**
   * 返回适用于from子句的表表达式
   * 
   * @return
   */
  public String getSQLFromExpression() throws BusinessException {
    StringBuffer sb = new StringBuffer();
    sb.append(query.translateTable(getName()));
    if (getAlias() != null)
      sb.append(" " + getSQLAlias());
    return sb.toString();
  }

  public String getSQLAlias() throws BusinessException {
    String tablename = query.translateTable(name);
    String suffix = alias.substring(name.length());
    String result = tablename + suffix;
    return result.replace('.', '_');
  }

  public void setSQLAlias(String value) throws BusinessException {
    String tablename = query.translateTable(name);
    tablename = tablename.replace('.', '_');
    String suffix = value.substring(tablename.length());
    if (!value.equals(tablename + suffix))
      suffix = value.substring(name.length());
    alias = name + suffix;
  }

  public String debugInfo() {
    StringBuffer sb = new StringBuffer();
    sb.append(getClass().getName() + "\n");
    sb.append("Name: " + getName() + "\n");
    sb.append("Alias: " + getAlias() + "\n");
    sb.append("IndexName: " + getIndexName() + "\n");
    sb.append("IndexMethod: " + getIndexMethod() + "\n");
    return sb.toString();
  }

  private String name;

  private String alias;

  private String indexName;

  private String indexMethod;

  public String getIndexMethod() {
    return indexMethod;
  }

  public void setIndexMethod(String indexMethod) {
    this.indexMethod = indexMethod;
  }

  public String getIndexName() {
    return indexName;
  }

  public void setIndexName(String indexName) {
    this.indexName = indexName;
  }

  public String getAlias() {
    return alias;
  }

  public void setAlias(String alias) {
    this.alias = alias;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  private QueryDefinition query;

  public QueryDefinition getQuery() {
    return query;
  }

  public void setQuery(QueryDefinition query) {
    this.query = query;
  }
}
